package com.siyu.tickets.dao.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.siyu.common.hibernate3.Finder;
import com.siyu.common.hibernate3.HibernateBaseDao;
import com.siyu.common.page.Pagination;
import com.siyu.tickets.dao.ProductDao;
import com.siyu.tickets.entity.Product;

@Repository
public class ProductDaoImpl extends HibernateBaseDao<Product, Integer> implements ProductDao {

	public Pagination getPage(String name, Date beginTime, Date endTime, Integer typeId, Integer groupId,
			Integer cityId, Integer supplierId, Boolean enable, int pageNo, int pageSize) {
		Finder f = Finder.create("select bean from Product bean");
		f.append(" where 1=1");
		if (!StringUtils.isBlank(name)) {
			f.append(" and ( bean.name like :name ");
			f.append(")");
			f.setParam("name", "%" + name + "%");
		}
		if (beginTime != null) {
			f.append(" and bean.beginTime >= :beginTime");
			f.setParam("beginTime", beginTime);
		}
		if (endTime != null) {
			f.append(" and bean.endTime <= :endTime");
			f.setParam("endTime", endTime);
		}
		if (typeId != null) {
			f.append(" and bean.type.id = :typeId");
			f.setParam("typeId", typeId);
		}
		if (groupId != null) {
			f.append(" and bean.group.id = :groupId");
			f.setParam("groupId", groupId);
		}
		if (cityId != null) {
			f.append(" and (bean.cityIds like :cityId1");
			f.append(" or bean.cityIds like :cityId2 ");
			f.append(" or bean.cityIds like :cityId3 ");
			f.append(")");
			f.setParam("cityId1", cityId + ",%");
			f.setParam("cityId2", "%," + cityId + ",%");
			f.setParam("cityId3", "%," + cityId);
		}
		if (supplierId != null) {
			f.append(" and bean.supplier.id = :supplierId");
			f.setParam("supplierId", supplierId);
		}
		if (enable != null) {
			f.append(" and bean.enable=:enable");
			f.setParam("enable", enable);
		}
		f.append(" order by bean.createTime desc");
		return find(f, pageNo, pageSize);
	}

	public Product findById(Integer id) {
		Product entity = get(id);
		return entity;
	}

	public Product save(Product bean) {
		getSession().save(bean);
		return bean;
	}

	public Product deleteById(Integer id) {
		Product entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	protected Class<Product> getEntityClass() {
		return Product.class;
	}

}
